import axios from 'axios'
import { useAuthStore } from '@/stores/authStore'
import { ElMessage } from 'element-plus'
import router from '@/router'

const apiClient = axios.create({
  baseURL: 'http://api.nonamenona.top/api',
  headers: {
    'Content-Type': 'application/json',
  },
})

const uploadClient = axios.create({
  baseURL: 'http://api.nonamenona.top/api',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
})

export function handleErrorAndRedirect(
  error: any,
  errorMsg = '请求失败',
  fallbackPath = '/dashboard',
  loginPath = '/login',
) {
  const authStore = useAuthStore()
  if (authStore.isAuthenticated) {
    ElMessage.error(errorMsg)
    router.push(fallbackPath)
  } else {
    router.push(loginPath)
  }
}

// 请求拦截器：在每个请求发送前，自动附加 JWT Token
apiClient.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    const token = authStore.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

uploadClient.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    const token = authStore.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error),
)

apiClient.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response) {
      const { status } = error.response
      const authStore = useAuthStore()

      if (status === 400) {
        ElMessage.error('用户名或密码错误')
      } else if (status === 401) {
        if (authStore.isAuthenticated) {
          ElMessage.error('您的登录已过期，请重新登录。')
          authStore.logout()
        }
        /* }else if (status === 403) {
          ElMessage.warning('您无权访问该资源。')*/
      }
    } else if (error.code === 'ERR_NETWORK') {
      ElMessage.error('网络错误，无法连接到服务器。')
    }
    return Promise.reject(error)
  },
)

export { apiClient, uploadClient }
